package com.fishingwithme.android.ui.viewmodels

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.model.User
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

@HiltViewModel
class UserEditViewModel @Inject constructor(
    private val repository: FishingRepository,
    private val preferencesManager: PreferencesManager
) : ViewModel() {

    private val _uiState = MutableStateFlow(UserEditUiState())
    val uiState: StateFlow<UserEditUiState> = _uiState.asStateFlow()

    // 设置初始数据
    fun setInitialData(user: User) {
        _uiState.value = _uiState.value.copy(
            nickname = user.nickname,
            avatarUrl = user.avatarUrl,
            username = user.username,
        )
    }

    fun clearError() {
        uiState.value.copy(
            error = ""
        )
    }

    // 设置昵称
    fun setNickname(nickname: String) {
        _uiState.value = _uiState.value.copy(nickname = nickname)
    }

    // 选择头像
    fun onAvatarSelected(avatarPath: String) {
        _uiState.value = _uiState.value.copy(avatarUrl = avatarPath)
    }

    // 上传头像文件并保存
    fun uploadAndSaveAvatar(file: File) {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            try {
                // First upload the file to get the URL
                repository.uploadFile(file).collect { result ->
                    result.fold(
                        onSuccess = { url ->
                            val params = mapOf("avatarUrl" to url)
                            repository.saveUserAvatar(params).collect { saveResult ->
                                saveResult.fold(
                                    onSuccess = {
                                        // Update the UI state with the new avatar URL
                                        _uiState.value = _uiState.value.copy(
                                            avatarUrl = url,
                                            error = null
                                        )
                                    },
                                    onFailure = {
                                        _uiState.value = _uiState.value.copy(
                                            error = "保存头像失败"
                                        )
                                    }
                                )
                            }
                        },
                        onFailure = { e ->
                            _uiState.value = _uiState.value.copy(
                                error = "上传头像失败: ${e.message ?: "未知错误"}"
                            )
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "上传头像失败: ${e.message}"
                )
                Log.e("UserEditViewModel", "Failed to upload avatar", e)
            } finally {
                _uiState.value = _uiState.value.copy(isLoading = false)
            }
        }
    }


    // 保存所有更改
    fun saveAllChanges() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            try {
                val nicknameMap = mapOf(Pair("nickname",_uiState.value.nickname?:""))
                repository.saveUserNickName(nicknameMap).collect { result ->
                    result.fold(
                        onSuccess = { nickname ->
                            _uiState.value = _uiState.value.copy(
                                nickname = nickname,
                                isSaveSuccessful = true
                            )
                        },
                        onFailure = { e ->
                            _uiState.value = _uiState.value.copy(
                                error = "上传头像失败: ${e.message ?: "未知错误"}",
                                isSaveSuccessful = false
                            )
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "更新成功"
                )
                Log.e("UserEditViewModel", "Failed to upload avatar", e)
            } finally {
                _uiState.value = _uiState.value.copy(isLoading = false)
            }
        }
    }

    // UI状态数据类
    data class UserEditUiState(
        var nickname: String? = "",
        val username: String = "",
        val avatarUrl: String = "",
        val isLoading: Boolean = false,
        val isSaveSuccessful: Boolean = false,
        val error: String? = null
    )
}